// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use, unused_import, avoid_print, unnecessary_brace_in_string_interps

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/tool/platformUtils/FFPlatform.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:mybase/base/abstract/IFFScaffold.dart';
import 'package:mybase/base/config/DeaultPageConfig.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/widget/page/FFScaffold.dart';

import 'IFFR.dart';
import 'IFFRequestControl.dart';

enum RefreshResultStatus {
  status_result,
  status_noData,
  status_timeout,
  status_netErr,
}

enum RefreshApiStatus {
  status_none, //未刷新
  status_refreshing_head, //正在刷新头
  status_refreshing_foot, //正在刷新尾
}

/**刷新接口 */
abstract class IFFRefresh {
  /**添加刷新组件 */
  Widget ffWidget(BuildContext ctx, Widget child, FFPageStatus status);

  /**刷新的状态*/
  RefreshApiStatus? ffrefreshApiStatus;

  /**是否有顶部刷新功能 */
  bool? ffCanRefreshHead();

  /**是否有底部刷新功能 */
  bool? ffCanRefreshFoot();

  /**去调接口 */
  ffRefresh(bool isHead);

  int getPage();

  setPage(int p);

  /**处理结果*/
  ffRefreshResult(bool isHead, Function(IRefreshParam? iRefreshParam) api,
      FFScaffoldState state);

  /**刷新控制 */

  /// 头部
  /// 头部
  /// 头部
  /**请求刷新 */
  Future<void> ffRequestRefresh();

  /**刷新顶部结束 */
  ffRefreshCompleted({RefreshResultStatus? resultStatus});

  /// 尾部
  /// 尾部
  /// 尾部
  /**加载更多结束 */
  ffLoadComplete({RefreshResultStatus? resultStatus});

  ///列表允许展示的最大条数
  int? ffMaxNumberOfLines();

  ///达到了最大值
  ffDidMaxNumber(bool didmax);
}

///注意：此抽象类里面不能写任何东西
abstract class IRefreshParam {}

/**android ios需要实现上下拉刷新的 */
class MFFRefresh implements IFFRefresh {
  ///刷新控件
  late RefreshController refreshController =
      RefreshController(initialRefresh: false);
  late ScrollController scrollController = ScrollController()..addListener(() {

    if (FFPlatform.isWeb && ffCanRefreshFoot() == true) {
      double maxScrollExtent = scrollController.position.maxScrollExtent;
      double pixels = scrollController.position.pixels;
      if (maxScrollExtent - pixels <= 120) {
        refreshController.requestLoading();
      }
    }

  });

  @override
  RefreshApiStatus? ffrefreshApiStatus = RefreshApiStatus.status_none;

  ///动画时间
  Duration duration = Duration(milliseconds: 800);

  Map<FFPageStatus, RefreshController> refreshMap = {
    FFPageStatus.netError: RefreshController(initialRefresh: false),
    FFPageStatus.noData: RefreshController(initialRefresh: false),
    FFPageStatus.result: RefreshController(initialRefresh: false),
    FFPageStatus.firstLoading: RefreshController(initialRefresh: false),
  };

  @override
  Widget ffWidget(BuildContext ctx, Widget child, FFPageStatus status) {

    refreshController = refreshMap[status]!;
    bool enablePullUp = ffCanRefreshFoot() ?? false;
    if (status == FFPageStatus.noData || status == FFPageStatus.netError) {
      enablePullUp = false;
    }
    return Container(
      child: SmartRefresher(
        enablePullDown: ffCanRefreshHead() ?? false,
        enablePullUp: enablePullUp,
        //header: ClassicHeader(),
        header: ClassicHeader(
          failedIcon: Icon(Icons.error, color: Colors.white),
          completeIcon: Icon(Icons.done, color: Colors.white),
          idleIcon: Icon(Icons.arrow_downward, color: Colors.white),
          releaseIcon: Icon(Icons.refresh, color: Colors.white),
          textStyle: TextStyle(color: Colors.white),
          refreshingIcon: SizedBox(
            width: 20.0,
            height: 20.0,
            child: FFPlatform.isIOS == true
                ? CupertinoActivityIndicator(color: Colors.white)
                : CircularProgressIndicator(
                    strokeWidth: 2.0, color: Colors.white),
          ),
          releaseText: DeaultPageConfig().releaseText != null
              ? DeaultPageConfig().releaseText!(ctx)
              : null,
          refreshingText: DeaultPageConfig().refreshingText != null
              ? DeaultPageConfig().refreshingText!(ctx)
              : null,
          canTwoLevelText: DeaultPageConfig().canTwoLevelText != null
              ? DeaultPageConfig().canTwoLevelText!(ctx)
              : null,
          completeText: DeaultPageConfig().completeText != null
              ? DeaultPageConfig().completeText!(ctx)
              : null,
          failedText: DeaultPageConfig().failedText != null
              ? DeaultPageConfig().failedText!(ctx)
              : null,
          idleText: DeaultPageConfig().idleText != null
              ? DeaultPageConfig().idleText!(ctx)
              : null,
        ),
        // footer: ClassicFooter(),
        footer: ClassicFooter(
          loadingIcon: SizedBox(
            width: 20.0,
            height: 20.0,
            child: FFPlatform.isIOS == true
                ? CupertinoActivityIndicator(color: Colors.white)
                : CircularProgressIndicator(
                    strokeWidth: 2.0, color: Colors.white),
          ),
          loadingText: DeaultPageConfig().loadingText != null
              ? DeaultPageConfig().loadingText!(ctx)
              : null,
          noDataText: DeaultPageConfig().noDataText != null
              ? DeaultPageConfig().noDataText!(ctx)
              : null,
          idleText: DeaultPageConfig().idleFootText != null
              ? DeaultPageConfig().idleFootText!(ctx)
              : null,
          failedText: DeaultPageConfig().failedFootText != null
              ? DeaultPageConfig().failedFootText!(ctx)
              : null,
          canLoadingText: DeaultPageConfig().canLoadingText != null
              ? DeaultPageConfig().canLoadingText!(ctx)
              : null,
        ),
        controller: refreshController,
        scrollController: scrollController,
        onRefresh: () {
          ffRefresh(true);
        },
        onLoading: () {
          ffRefresh(false);
        },
        child: child,
      ),
    );
  }

  @override
  bool? ffCanRefreshFoot() {
    return false;
  }

  @override
  bool? ffCanRefreshHead() {
    return false;
  }

  @override
  ffRefreshResult(bool isHead, Function(IRefreshParam? iRefreshParam) api,
      FFScaffoldState? state,
      {IRefreshParam? iRefreshParam}) async {
    if (isHead) {
      ffrefreshApiStatus = RefreshApiStatus.status_refreshing_head;
    } else {
      ffrefreshApiStatus = RefreshApiStatus.status_refreshing_foot;
    }

    if (isHead) {
      setPage(1);
    }

    //开始请求
    MFFRequestControl requestControl = MFFRequestControl();
    //拿到结果
    IFFR r = await requestControl.ffApiIs(api, iRefreshParam);
    ffrefreshApiStatus = RefreshApiStatus.status_none;

    ///错误页 无数据也能刷新 需要处理
    if (r.rStatus == RStatus.noData || r.rStatus == RStatus.error) {
      if (refreshController.headerStatus == RefreshStatus.refreshing) {
        if (r.rStatus == RStatus.error) {
          refreshController.refreshFailed();
        } else if (r.rStatus == RStatus.noData) {
          refreshController.refreshCompleted();
        }
      }
    }

    //根据请求结果区分
    if (isHead == true) {
      ffDidMaxNumber(false);
      //头刷新
      switch (r.rStatus) {
        case RStatus.result: //有结果
          {
            state?.datas = [];

            if (!FFEmpty.listIsEmpty(r.data)) {
              List dataList = r.data as List;
              for (int i = 0; i < dataList.length; i++) {
                state?.datas.add(dataList[i]);
              }
            }

            setPage(getPage() + 1);
            if (state?.iffScaffold.ffPageStatus == FFPageStatus.firstLoading) {
              //当前是第一次进来
              state?.iffScaffold.ffPageStatus = FFPageStatus.result;
            } else if (state?.iffScaffold.ffPageStatus == FFPageStatus.result) {
              state?.iffScaffold.ffPageStatus = FFPageStatus.result;
              // 当前结果页
              ffRefreshCompleted(
                  resultStatus: RefreshResultStatus.status_result);
            } else if (state?.iffScaffold.ffPageStatus ==
                    FFPageStatus.netError ||
                state?.iffScaffold.ffPageStatus == FFPageStatus.noData) {
              //当前错误页 或者 无数据页
              ffRefreshCompleted(
                  resultStatus: RefreshResultStatus.status_result);
              await Future.delayed(duration, () {
                state?.iffScaffold.ffPageStatus = FFPageStatus.result;
              });
            }

            break;
          }
        case RStatus.noData:
          {
            if (state?.iffScaffold.ffPageStatus == FFPageStatus.netError ||
                state?.iffScaffold.ffPageStatus == FFPageStatus.result) {
              //从错误页过来
              await Future.delayed(duration, () {
                state?.iffScaffold.ffPageStatus = FFPageStatus.noData;
              });
            } else {
              state?.iffScaffold.ffPageStatus = FFPageStatus.noData;
            }
            break;
          }
        case RStatus.error:
          {
            if (state?.iffScaffold.ffPageStatus == FFPageStatus.noData ||
                state?.iffScaffold.ffPageStatus == FFPageStatus.result) {
              //从无数据页过来
              await Future.delayed(duration, () {
                state?.iffScaffold.ffPageStatus = FFPageStatus.netError;
              });
            } else {
              state?.iffScaffold.ffPageStatus = FFPageStatus.netError;
            }
            break;
          }
        case RStatus.timeout:
          {
            state?.iffScaffold.ffPageStatus = FFPageStatus.netError;

            break;
          }
      }
    } else {
      //尾刷新
      switch (r.rStatus) {
        case RStatus.result: //有结果
          {
            state?.datas.addAll(r.data);
            int length = state?.datas.length ?? 0;
            int maxLength = ffMaxNumberOfLines() ?? 999999999;
            if (length > maxLength) {
              //超过了最大的值

              var obj = state?.datas.sublist(0, maxLength);
              state?.datas = obj ?? [];
              ffDidMaxNumber(true);
              ffLoadComplete(resultStatus: RefreshResultStatus.status_noData);
            } else {
              ffDidMaxNumber(false);
              setPage(getPage() + 1);
              ffLoadComplete(resultStatus: RefreshResultStatus.status_result);
            }
            break;
          }
        case RStatus.noData:
          {
            ffLoadComplete(resultStatus: RefreshResultStatus.status_noData);
            break;
          }
        case RStatus.error:
          {
            ffLoadComplete(resultStatus: RefreshResultStatus.status_netErr);
            break;
          }
        case RStatus.timeout:
          {
            ffLoadComplete(resultStatus: RefreshResultStatus.status_timeout);
            break;
          }
      }
    }

    state?.setState(() {});
  }

  @override
  ffRefresh(bool isHead) {
    if (isHead) {
      ffRefreshCompleted();
    } else {
      ffLoadComplete();
    }
  }

  @override
  Future<void> ffRequestRefresh() async {
    await refreshController.requestRefresh();
  }

  @override
  ffRefreshCompleted(
      {RefreshResultStatus? resultStatus = RefreshResultStatus.status_result}) {
    switch (resultStatus) {
      case RefreshResultStatus.status_result:
        {
          refreshController.refreshCompleted();
          refreshController.resetNoData();
          break;
        }
      case RefreshResultStatus.status_noData:
        {
          refreshController.refreshCompleted();
          break;
        }
      case RefreshResultStatus.status_timeout:
        {
          refreshController.refreshFailed();
          break;
        }
      case RefreshResultStatus.status_netErr:
        {
          refreshController.refreshFailed();
          break;
        }
    }
  }

  @override
  ffLoadComplete(
      {RefreshResultStatus? resultStatus = RefreshResultStatus.status_result}) {
    switch (resultStatus) {
      case RefreshResultStatus.status_result:
        {
          refreshController.loadComplete();
          break;
        }
      case RefreshResultStatus.status_noData:
        {
          refreshController.loadNoData();
          break;
        }
      case RefreshResultStatus.status_timeout:
        {
          refreshController.loadFailed();
          break;
        }
      case RefreshResultStatus.status_netErr:
        {
          refreshController.loadFailed();
          break;
        }
    }
  }

  int page = 0;

  @override
  int getPage() {
    return page;
  }

  @override
  setPage(int p) {
    page = p;
  }

  @override
  int? ffMaxNumberOfLines() {}

  @override
  ffDidMaxNumber(bool didmax) {}
}
